package com.sunseagear.common.base.http;

import cn.hutool.http.HttpStatus;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.List;

/**
 * 响应信息主体
 *
 */
@Data
@NoArgsConstructor
public class R<T> implements Serializable {

    public static final int DEFAULT_SUCCESS_CODE = HttpStatus.HTTP_OK;
    public static final int DEFAULT_FAIL_CODE = HttpStatus.HTTP_INTERNAL_ERROR;

    public static final String DEFAULT_SUCCESS_MSG = "操作成功";
    public static final String DEFAULT_FAIL_MSG = "操作失败";


    /**
     * 返回值，是否成功
     */
    private boolean success;
    /**
     * 列表数据
     */
    private T data;

    /**
     * 消息状态码
     */
    private int code;

    /**
     * 消息内容
     */
    private String msg;


    @NotNull
    public static <T> R<T> success() {
        return restResult(DEFAULT_SUCCESS_CODE, DEFAULT_SUCCESS_MSG, null);
    }

    @NotNull
    public static <T> R<T> success(T data) {
        return restResult(DEFAULT_SUCCESS_CODE, DEFAULT_SUCCESS_MSG, data);
    }

    @NotNull
    public static <T> R<T> success(String msg) {
        return restResult(DEFAULT_SUCCESS_CODE, msg, null);
    }

    @NotNull
    public static <T> R<T> success(String msg, T data) {
        return restResult(DEFAULT_SUCCESS_CODE, msg, data);
    }

    @NotNull
    public static <T> R<T> success(int code, String msg) {
        return restResult(code, msg, null);
    }

    @NotNull
    public static <T> R<T> fail() {
        return restResult(DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, null);
    }

    @NotNull
    public static <T> R<T> fail(String msg) {
        return restResult(DEFAULT_FAIL_CODE, msg, null);
    }

    @NotNull
    public static <T> R<T> fail(T data) {
        return restResult(DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, data);
    }

    @NotNull
    public static <T> R<T> fail(String msg, T data) {
        return restResult(DEFAULT_FAIL_CODE, msg, data);
    }

    @NotNull
    public static <T> R<T> fail(int code, String msg) {
        return restResult(code, msg, null);
    }

    @NotNull
    private static <T> R<T> restResult(int code, String msg, T data) {
        return restResult(R.DEFAULT_SUCCESS_CODE == code, code, msg, data);
    }

    @NotNull
    private static <T> R<T> restResult(boolean success, int code, String msg, T data) {
        R<T> r = new R<>();
        r.setSuccess(success);
        r.setCode(code);
        r.setData(data);
        r.setMsg(msg);
        return r;
    }
}
